package com.siemens.industrial.web.mvc.controller.partner.user;

import com.siemens.industrial.model.admin.SystemConfig;
import com.siemens.industrial.model.admin.Tenant;
import com.siemens.industrial.model.partner.Device;
import com.siemens.industrial.model.partner.Event;
import com.siemens.industrial.model.partner.User;
import com.siemens.industrial.utils.GlobalResponseCode;
import com.siemens.industrial.utils.JsonToOtherFormat;
import com.siemens.industrial.utils.RestResponse;
import com.siemens.industrial.utils.SiemensException;
import com.siemens.industrial.web.mvc.pojo.DataTableQuery;
import com.siemens.industrial.web.mvc.service.AuthService;
import com.siemens.industrial.web.mvc.service.WriteLogs;
import com.siemens.industrial.web.mvc.service.admin.SystemConfigService;
import com.siemens.industrial.web.mvc.service.admin.TenantService;
import com.siemens.industrial.web.mvc.service.partner.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by qupen on 2016/9/1.
 */
@Controller
public class PartnerUserIdleController {
    @Resource
    PartnerUserService partnerUserService;

    @Resource
    PartnerIdleService partnerIdleService;

    @Resource
    TenantService tenantService;

    @Resource
    AuthService authService;

    @Resource
    PartnerMetadataService partnerMetadataService;

    @Resource
    PartnerEventService partnerEventService;

    @Resource
    SystemConfigService systemConfigService;

    @Resource
    PartnerDeviceService partnerDeviceService;

    @Resource
    WriteLogs writeLogs;

    @RequestMapping(value = "/partner/{tenant}/user/idles", method = RequestMethod.GET)
    public String getIdles(@PathVariable("tenant") String tenantKey, Map<String, Object> map, ModelMap modelMap) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        modelMap.put("key", tenantKey);
        map.put("idles", partnerIdleService.getDeviceIdleInfoList(tenantId));
        return "partner/user/idle/index";
    }

    @RequestMapping(value = "/partner/{tenant}/user/downtimeRecord",method = RequestMethod.GET)
    public String getDowntimeRecord(@PathVariable("tenant") String tenantKey){
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        return "partner/user/downtime_record";
    }

    @RequestMapping(value = "/partner/{tenant}/user/idle", method = RequestMethod.GET)
    public String getIdle(@PathVariable("tenant") String tenantKey, @RequestParam(value="userId", required = true) String userId, Map<String, Object> map,ModelMap modelMap) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        map.put("key",tenantKey);
        map.put("user", partnerUserService.getUser(tenantKey, tenantId, userId));
        return "partner/user/idle/index";
    }

    @RequestMapping(value = "/partner/{tenant}/user/idle/create", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> createIdle(@PathVariable("tenant") String tenantKey, @RequestBody Map<String, Object> map) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        User user = (User) authService.currentUser();
        int i = 0;
        try {
          i = partnerIdleService.saveDeviceIdleInfo(tenantId,map,user);
        } catch (SiemensException e) {
            e.printStackTrace();
        }
        if(i == 1){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            User currentUser = (User) authService.currentUser();
            Device device = partnerDeviceService.getDeviceById(tenantId,map.get("deviceId").toString());
            String content = currentUser.getUserName()+"于"+ simpleDateFormat.format(new Date())+"添加了机床"+"\""+device.getDeviceUniqueId()+"\"的IDLE原因。";
            writeLogs.writeLog(SystemConfig.LOG_USER_OPERATE_KEY,content,tenantKey+"_operate");
            String reasonId = map.get("reasonId").toString();
            String metaDefinition = partnerMetadataService.getMetadata(tenantId,reasonId).getMetaDefinition();
            Map<String,Object> objectMap = JsonToOtherFormat.buildJsonToMap(metaDefinition);
            if(objectMap.get("IDLEEvent") != null){
                if (objectMap.get("IDLEEvent").equals(true)){
                    Event event= partnerEventService.getOneByName(tenantId,objectMap.get("IDLEReason").toString());//判断事件是否被删除
                    if (event!=null){
                        partnerEventService.insertMessage(tenantId,event.getEventId(),0,partnerDeviceService.getDevice(tenantId,map.get("deviceId").toString()).getDeviceUniqueId(), map.get("startTime").toString(), map.get("endTime").toString(),objectMap.get("IDLEReason").toString());
                        String[] mails = partnerEventService.isSubscriptionTheEventByDeviceIdOrGroupOrLine(tenantId,event.getEventId(),device.getDeviceId(),device.getGroup(),device.getLine());
                        if (mails!=null){
                            systemConfigService.sendMail(mails,"事件触发通知","机床"+partnerDeviceService.getDevice(tenantId,map.get("deviceId").toString()).getDeviceUniqueId()+"于"+map.get("startTime")+"--"+map.get("endTime")+"触发了事件"+objectMap.get("IDLEReason"));
                        }
                    }
                }
            }
            return RestResponse.create(GlobalResponseCode.SUCCESS).build();
        }else{
            return RestResponse.create(GlobalResponseCode.ERROR_CREATE_REASON_FAIL).build();
        }
    }

    @RequestMapping(value = "/partner/{tenant}/user/idle/getOneReason",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getOneReason(@PathVariable("tenant") String tenantKey,String deviceId,String startTime){
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        Map map = partnerIdleService.getDeviceIdleInfo(tenantId,deviceId,startTime);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(map).build();
    }

    @RequestMapping(value = "/partner/{tenant}/user/idle/edit", method = RequestMethod.POST)
    public String editIdle(@PathVariable("tenant") String tenantKey, @RequestParam(value="userId", required = true) String userId, Map<String, Object> map,ModelMap modelMap) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        modelMap.put("key", tenantKey);
        map.put("user", partnerUserService.getUser(tenantKey, tenantId, userId));
        return "partner/user/idle/index";
    }

    @RequestMapping(value = "/partner/{tenant}/user/idle/delete", method = RequestMethod.POST)
    public String deleteIdle(@PathVariable("tenant") String tenantKey, @RequestParam(value="userId", required = true) String userId, Map<String, Object> map,ModelMap modelMap) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        modelMap.put("key", tenantKey);
        map.put("user", partnerUserService.getUser(tenantKey, tenantId, userId));
        return "partner/user/idle/index";
    }

    @RequestMapping(value = "/partner/{tenant}/user/idle/reason",method = RequestMethod.GET)
    public String idleReason(@PathVariable("tenant") String tenantKey, ModelMap modelMap){
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        modelMap.put("key",tenantId);
        return "partner/user/idle_reason";
    }

    @RequestMapping(value = "/partner/{tenant}/user/idle/reason/getDeviceType",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getDeviceType(@PathVariable("tenant") String tenantKey){
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        List<String> list = partnerIdleService.getDeviceType(tenantId);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(list).build();
    }

    @RequestMapping(value = "/partner/{tenant}/user/idle/reason/getDeviceModel",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getDeviceModelAndUniqueId(@PathVariable("tenant") String tenantKey,
                                                        @RequestParam(name="deviceType") String deviceType){
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        List<String> list = partnerIdleService.getDeviceModel(tenantId,deviceType);
//        Map<String,Object> map = partnerIdleService.getDeviceModelAndUniqueId(tenantId,deviceType);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(list).build();
    }

    @RequestMapping(value = "/partner/{tenant}/user/idle/reason/getDeviceUniqueId",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getDeviceUniqueId(@PathVariable("tenant") String tenantKey,
                                                @RequestParam(name="deviceType") String deviceType,
                                                @RequestParam(name="deviceModel") String deviceModel){
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        List<Map<String,Object>> list = partnerIdleService.getDeviceUniqueId(tenantId,deviceType,deviceModel);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(list).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/faultReason/list",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getFaultList(@PathVariable("tenant") String tenantKey){
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        List<Map<String,Object>> faultList = partnerIdleService.getFaults(tenantId);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(faultList).build();
    }

    @RequestMapping(value = "/partner/{tenant}/faultReason/list",method = RequestMethod.GET)
    public String getFaultListPage(@PathVariable("tenant") String tenantKey){
        return "partner/user/repair_info_list";
    }

    @RequestMapping(value = "/partner/{tenant}/maintain/info",method = RequestMethod.GET)
    public String getMaintainInfoPage(@PathVariable("tenant") String tenantKey,
                                      String deviceId,String startTime,String endTime,ModelMap modelMap){
        modelMap.put("deviceId",deviceId);
        modelMap.put("startTime",startTime);
        modelMap.put("endTime",endTime);
        return "partner/user/fault_recorded";
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/faultReason/update",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> addMaintainInfo(@PathVariable("tenant") String tenantKey,
                                              @RequestBody Map<String,Object> data){
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        try {
            partnerIdleService.updateDeviceIdleInfo(tenantId,data.get("deviceId").toString(),data.get("idleStartTime").toString(),data);
            return RestResponse.create(GlobalResponseCode.SUCCESS).build();
        } catch (SiemensException e) {
            e.printStackTrace();
            return new HashMap<>();
        }
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/getDowntimeRecordList",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getDowntimeRecordList(@PathVariable("tenant") String tenantKey){
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        List<Map<String,Object>> list = partnerIdleService.getDowntimeRecordList(tenantId);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(list).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/messages",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getMessages(@PathVariable("tenant") String tenantKey,
                                          @RequestParam(name ="mtid" ,required = false) String mtid,
                                          @RequestParam(name ="startTime" ,required = false) String startTime,
                                          @RequestParam(name ="endTime" ,required = false) String endTime,
                                          @RequestParam(name ="idle" ,required = false) String idle,
                                          @RequestParam(name ="status" ,required = false) String status){
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        List<Map<String,Object>> list = partnerIdleService.getAllMessage(tenantId,mtid,startTime,endTime,idle,status);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(list).build();
    }

    @RequestMapping(value = "/partner/{tenant}/message/list",method = RequestMethod.GET)
    public String getMessagesPage(@PathVariable("tenant") String tenantKey){
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        return "partner/user/messages";
    }

    //获取全部的idleReason
    @RequestMapping(value = "/partner/{tenant}/api/v1/idle/getIdleReasonList", method = RequestMethod.GET)
    @ResponseBody
    public Map getIdleReasonList(@PathVariable("tenant") String tenantKey) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();

        List idleReason = partnerIdleService.getIdleReasons(tenantId);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(idleReason).build();
    }

    //获取全部故障
    @RequestMapping(value = "/partner/{tenant}/api/v1/idle/getFaultType", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getFaultType(@PathVariable("tenant") String tenantKey) {
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();

        List faultType = partnerIdleService.getFaultType(tenantId);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(faultType).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/user/oneByKey", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getOneByKey(@PathVariable("tenant") String tenantKey) {
        Tenant tenant = tenantService.getTenantByKey(tenantKey);
        String logo = tenant.getLogoMd5();
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(logo).build();
    }

    //dataTable search fault reason
    @RequestMapping(value = "/partner/{tenant}/api/v1/faultReasonsByDataTable",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getFaultListByDataTable(@PathVariable("tenant") String tenantKey,
                                                      HttpServletRequest request){
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        DataTableQuery dt = new DataTableQuery(request);

        if (dt.isDataTableRequest()){
            Map<String,Object> faultList = partnerIdleService.getFaultsByDataTable(tenantId,request);
            return faultList;
        }
        List<Map<String,Object>> faultList = partnerIdleService.getFaults(tenantId);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(faultList).build();
    }

    @RequestMapping(value = "/partner/{tenant}/api/v1/messagesByDataTable",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getMessagesByDataTable(@PathVariable("tenant") String tenantKey,
                                          @RequestParam(name ="mtid" ,required = false) String mtid,
                                          @RequestParam(name ="startTime" ,required = false) String startTime,
                                          @RequestParam(name ="endTime" ,required = false) String endTime,
                                          @RequestParam(name ="idle" ,required = false) String idle,
                                          @RequestParam(name ="status" ,required = false) String status,
                                                     HttpServletRequest request){
        String tenantId = tenantService.getTenantByKey(tenantKey).getTenantId();
        DataTableQuery dt = new DataTableQuery(request);

        if (dt.isDataTableRequest()){
            Map map = partnerIdleService.getAllMessageByDataTable(tenantId,mtid,startTime,endTime,idle,status,request);
            return map;
        }
        return dt.buildResponse(0,0,new ArrayList<>());
    }
}
